"""
#!/usr/bin/python3
# coding:utf-8            
#
# Copyright (C) 2024 - 2024 Jasonakeke， Inc. All Rights Reserved 
# @Desc	   ：
# @Time    : 2024/8/25 17:14
# @Author  : Code_By_Jasonakeke
# @Email   : 2284037977@qq.com
# @File    : 01_api.py
# @IDE     : PyCharm
"""
from json import dumps
from flask import Flask, current_app, make_response
from flask_restful import Api, Resource, marshal_with, marshal
from flask_restful.fields import String
from flask_restful.utils import PY3

app = Flask(__name__)

# 需求：对外提供一个 API 接口，可以访问某个资源，一共有三个步骤
# 步骤一：创建 restful 的 API
api = Api(app)


class User(object):
	def __init__(self, username, password, user_id):
		self.username = username
		self.password = password
		self.user_id = user_id


# 为了把模型对象转换成字典，在 marshal 里面必须定义一个属性转换格式
property_fields = {
	'password': String,
	'username': String,
}


@api.representation('application/json')
def output_json(data, code, headers = None):
	"""Makes a Flask response with a JSON encoded body"""
	# 此处添加自己定义的 json 格式规则
	if 'message' not in data:
		data = {
			'messsage': 'OK',
			'data': data
		}
	settings = current_app.config.get('RESTFUL_JSON', {})

	# If we're in debug mode, and the indent is not set, we set it to a
	# reasonable value here.  Note that this won't override any existing value
	# that was set.  We also set the "sort_keys" value.
	if current_app.debug:
		settings.setdefault('indent', 4)
		settings.setdefault('sort_keys', not PY3)

	# always end the json dumps with a new line
	# see https://github.com/mitsuhiko/flask/pull/1262
	dumped = dumps(data, **settings) + "\n"

	resp = make_response(dumped, code)
	resp.headers.extend(headers or {})
	return resp


# 步骤二：定义资源
class HelloResource(Resource):
	# 定义各种操作（函数）
	# @marshal_with(property_fields, envelope = 'data1')
	def get(self):
		user = User('jasonakeke', '123456', '1')
		return marshal(user, property_fields, envelope = 'data1')

	def put(self):
		return {'put': 'world'}

	def post(self):
		return {'post': 'world'}


# 步骤三，把资源加载到 api 中才能对外发布
api.add_resource(HelloResource, '/hello')

# app.run 可以省略
if __name__ == '__main__':
	app.run(debug = True)
